package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVoService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.util.AjaxResult;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.ControllerUtil;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/travel")
public class TravelController {

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private ITravelStatisVoService travelStatisVoService;

    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo") TravelQuery qo) {
        // pageInfo
        PageInfo<Travel> pageInfo = travelService.queryForList(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "travel/list";
    }

    @RequestMapping("/detail")
    public Object detail(Long id, Model model, @UserParam UserInfo userInfo) {
        //detail
        Travel travel = travelService.queryDetailById(id);
        model.addAttribute("detail", travel);
        travel.setTravelContent(travelService.getContentById(id));
        Long destId = travel.getDest().getId();
        // 共享导航
        ControllerUtil.setToastsToModel(destinationService, model, destId);
        // sds 查询相关地区的前三个攻略
        model.addAttribute("sds", strategyDetailService.queryDetailTop3(destId));
        // ts 查询相关地区的排名前三的游记
        TravelQuery travelQuery = new TravelQuery();
        travelQuery.setDestId(destId);
        model.addAttribute("ts", travelService.queryDetailTop3(travelQuery));
        // 查询评论
        model.addAttribute("list", travelCommentService.queryById(id));
        // 增加当前游记的阅读数
        travelStatisVoService.addTravelViewnumUp(id, 1);
        model.addAttribute("travelVo", travelStatisVoService.getTravelStatisVoByTravelId(id));
        // 查出当前用户收藏的所有游记
        if (userInfo != null) {
            model.addAttribute("travelIds", travelStatisVoService.queryUserFavorTravel(userInfo.getId()));
        }
        return "travel/detail";
    }

    @RequestMapping("/input")
    @RequiredLogin
    public String input(Model model, Long id) {
        // dests
        model.addAttribute("dests", destinationService.getDestsByDeep(3));
        // 查询游记信息
        if (id != null) {
            Travel travel = travelService.queryDetailById(id);
            travel.setTravelContent(travelService.getContentById(travel.getId()));
            model.addAttribute("tv", travel);
        }
        return "travel/input";
    }

    @Value("${file.path}")
    private String basePath;

    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, basePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredLogin
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }

    @RequestMapping("/commentAdd")
    public Object commentAdd(Model model, TravelComment comment, @UserParam UserInfo userInfo) {
        TravelComment travelComment = travelCommentService.saveOrUpdate(comment, userInfo);
        model.addAttribute("c", travelComment);
        model.addAttribute("floor", travelCommentService.countFloor(comment.getTravelId()));
        travelStatisVoService.addCommentUp(comment.getTravelId());
        return "travel/commentTpl";
    }

    @RequestMapping("/thumbsupnum")
    @ResponseBody
    public AjaxResult thumbsupnum(Long travelId, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "没有登录请先登录");
            result.setCode(102);
            return result;
        }
        // 添加顶的次数
        try {
            // 判断 该用户今天是否已经顶过, 如果没有定则 添加, 定的数量
            if (!travelStatisVoService.addThumbsUp(travelId, userInfo.getId())) {
                return new AjaxResult(false, "今天已经顶过, 明天再试~");
            }
        } catch (LogicException e) {
            return new AjaxResult(false, e.getMessage());
        } catch (Exception e) {
            return new AjaxResult(false, "系统繁忙, 请稍后重试~");
        }
        // 查询 当前游记的统计数据
        return AjaxResult.SUCCESS.addData(travelStatisVoService.getTravelStatisVoByTravelId(travelId));
    }

    @RequestMapping("/favornum")
    @ResponseBody
    public AjaxResult favornum(Long travelId, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "没有登录请先登录");
            result.setCode(102);
            return result;
        }
        boolean ret = travelStatisVoService.addFavornumUp(travelId, userInfo.getId());
        // 查询 当前游记的统计数据
        return new AjaxResult(ret, "").addData(travelStatisVoService.getTravelStatisVoByTravelId(travelId));
    }

    @RequestMapping("/share")
    @ResponseBody
    public AjaxResult share(@UserParam UserInfo userInfo, Long id) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult(false, "没有登录请先登录");
            result.setCode(102);
            return result;
        }
        try {
            travelStatisVoService.sharenumUp(id, userInfo.getId());
            return new AjaxResult(true, "").addData(travelStatisVoService.getTravelStatisVoByTravelId(id));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.FAIL;
        }
    }


}
